<?php
/**
 * Created by PhpStorm.
 * User: Kevin
 * Date: 2019/1/19
 * Time: 9:24
 */
namespace app\home\controller;
use think\Controller;
use think\Db;
use wxpay\Wxpay;
use alipay\Alipay;

class Callback extends Controller
{
    //支付宝回调处理订单
    public function doOrder(){
        extract(input());
        $pay = new Alipay();
        $info = $pay->checkReturn(input());//支付宝验签 返回bool
        if($trade_status == "TRADE_SUCCESS" && $info){
            if ($this->doneOrder($out_trade_no, $trade_no, $gmt_payment)) {
                //通知和推送
                return true;
            } else {
                return false;
            }
        }
        //{"gmt_create":"2019-01-17 16:22:56","charset":"UTF-8","gmt_payment":"2019-01-17 16:23:03","notify_time":"2019-01-17 16:23:04","subject":"上海市","sign":"j\/FM9QaLf8OcnhQMDFWgya80LCktk3WlcpQHXpHPu3Uw1RO6z4BUzYmzneA+ys3BHl91K4xu+YPb2DD6my\/9yfMevJ76tzjL6NpOfCM+owQfXYZhugLXpCIYY1lAacnsdBKEiuxDyYJ0XH9FYf7nWdLRLrmTelwpcMNZCPTo\/5yRDeyoK029kB1b8S+Mijs\/zU8hvKyofeWJ5inambSClAOlbw1pAXTxK8HAIE6tmOT5aZrbbzQdcpCGziXj2Q7xurHYFs\/kXe3\/HLVYvI1uq2XBccEs5oORHvuTWe0J+G52bP3961V\/zxM5LyzpNYKk2qQq0Voj88X7SI0FVydAiQ==","buyer_id":"2088102175404181","body":"购买商品2件共15.00元","invoice_amount":"1000.00","version":"1.0","notify_id":"ee5b2827cb4dca266b449e88860d4f8he5","fund_bill_list":"[{\"amount\":\"1000.00\",\"fundChannel\":\"ALIPAYACCOUNT\"}]","notify_type":"trade_status_sync","out_trade_no":"2131231321312","total_amount":"1000.00","trade_status":"TRADE_SUCCESS","trade_no":"2019011722001404180500552213","auth_app_id":"2016082100302870","receipt_amount":"1000.00","point_amount":"0.00","app_id":"2016082100302870","buyer_pay_amount":"1000.00","sign_type":"RSA2","seller_id":"2088102172375554"}
    }


    /**
     * 微信回调处理订单
     */
    public function backWx(){
        $check = new Wxpay();
        $check->wxCheckSing(function($result){
            //签名通过返回array
            //查询订单号，不存在return
            //查询订单是否被处理过，处理过return
            //处理订单
            if($result && $result['result_code'] == "SUCCESS" && $result['return_code'] == "SUCCESS"){
                extract($result);
                if ($this->doneOrder($out_trade_no, $transaction_id, $this->getDateBytimeDate($time_end))) {
                    //通知和推送
                }
                $str='<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';// 返回状态给微信服务器
            }else{
                $str='<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名失败]]></return_msg></xml>';// 返回状态给微信服务器
            }
            echo $str;
        });
        //{"appid":"wx5518b83be52f8d41","bank_type":"CFT","cash_fee":"1","fee_type":"CNY","is_subscribe":"N","mch_id":"1513192391","nonce_str":"w1e22gm65vsbtde8yw8s39a0aegnasov","openid":"ojxZQ5taQw09OdVwmbZ8dXMTKRqU","out_trade_no":"201901191424505723168","result_code":"SUCCESS","return_code":"SUCCESS","sign":"E514D16D676EA3E5581029CB0F260F58AAA609DBB532C3B7631C120736DD8564","time_end":"20190119142503","total_fee":"1","trade_type":"NATIVE","transaction_id":"4200000254201901190284378341"}
    }

    /**
     * 获取时间
     * @return array
     */
    public function getDateBytimeDate($string){
        $replacement = '-';
        $replacement2 = ':';
        $a = substr_replace($string, $replacement, 4, 0);
        $b = substr_replace($a, $replacement, 7, 0);
        $c = substr_replace($b, ' ', 10, 0);
        $d = substr_replace($c, $replacement2, 13, 0);
        $e = substr_replace($d, $replacement2, 16, 0);
        return $e;
    }
    public function getWxStatus()
    {
        extract(input());
        $status = Db::name('order')->where(['order_id'=>$oid])->value('order_status');
        if($status == 2){
            return json(['status'=>200,'oid'=>$oid]);
        }else{
            return json(['status'=>100,'oid'=>$oid]);
        }
    }
    public function doneOrder($number,$transaction_id,$paytime)
    {
        Db::startTrans();
        try{
            $order = Db::table('up_order')->where('order_number', $number)->find();
            if(!$order || $order['order_status'] == 2){
                return false;
            }
            //1、支付成功改状态
            $update = array();
            $update['order_status'] = 2;
            $update['order_back_transaction_id'] = $transaction_id;
            $update['order_paytime'] = $paytime;
            Db::table('up_order')
                ->where('order_number', $number)
                ->update($update);
            //1-2、改会员时长或包数量
            $type = $order['order_type'];//1是会员购买 2是置顶包 3是刷新包
            if($type == 1){
                $update2 = array();
                $update2['user_auth'] = $order['order_auth_type'];
                $update2['user_auth_start'] = $order['order_auth_begin'];
                $update2['user_auth_end'] = $order['order_auth_end'];
                Db::table('up_u_user')
                    ->where('user_id',$order['order_user_id'])
                    ->update($update2);
            }elseif ($type == 2){
                Db::table('up_u_user')
                    ->where('user_id',$order['order_user_id'])
                    ->setInc('user_mytop');
            }elseif ($type == 3){
                Db::table('up_u_user')
                    ->where('user_id',$order['order_user_id'])
                    ->setInc('user_myfresh');
            }else{
                Db::rollback();
                return false;
            }
            Db::commit();
            return true;
        }catch (\Exception $e) {
            Db::rollback();
            return false;
        }

    }
}